package main

import (
	"fmt"
	"sync"
	"time"
)

func main() {
	n1 := time.Now()
	old()
	n2 := time.Now()
	good()
	n3 := time.Now()

	print(n2.Sub(n1).Seconds())
	print(n3.Sub(n2).Seconds())
}

func old() {
	var mu sync.Mutex
	var counter int
	for i := 0; i < 100000; i++ {
		go func(i int) {
			if i%100 == 0 {
				mu.Lock()
				defer mu.Unlock()
				counter++
				return
			}
			//这里不加锁的话，值还会出问题
			mu.Lock()
			defer mu.Unlock()
			fmt.Printf("%5d: %d\n", i, counter)
		}(i)
	}
	//<-time.After(time.Second * 5)
}

func good() {
	var mu sync.RWMutex
	var counter int
	for i := 0; i < 100000; i++ {
		go func(i int) {
			if i%100 == 0 {
				mu.Lock()
				defer mu.Unlock()
				counter++
				return
			}
			//这里不加锁的话，值还会出问题
			mu.RLock()
			defer mu.RUnlock()
			fmt.Printf("%5d: %d\n", i, counter)
		}(i)
	}
	//<-time.After(time.Second * 5)
}
